from user import models
from rest_framework import serializers
import re

#验证邮箱
def checkemail(value):
    if not re.match(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$', value):
        raise serializers.ValidationError("邮箱格式不正确")
    else:
        emaildata = models.UserModel.objects.filter(email=value)
        if emaildata:
            raise serializers.ValidationError("邮箱已存在")

#验证手机号
def checkphone(value):
    if not re.match(r'^1[3456789]\d{9}$', value):
        raise serializers.ValidationError("手机号格式不正确")
    else:
        phonedata = models.UserModel.objects.filter(phone=value)
        if phonedata:
            raise serializers.ValidationError("手机号已存在")

#验证密码
def checkpassword(value):
    if not re.match(r'^[a-zA-Z0-9]{6,10}$', value):
        raise serializers.ValidationError("密码格式不正确")

class SerUser(serializers.ModelSerializer):
    class Meta:
        model = models.UserModel
        fields = "__all__"
        extra_kwargs = {
            "email":{
                "error_messages":{
                    "required":"邮箱不能为空",
                    "unique":"邮箱已存在"
                },
                "validators":[checkemail]
            },
            "phone":{
                "error_messages":{
                    "required":"手机号不能为空",
                    "unique":"手机号已存在"
                },
                "validators": [checkphone]
            },
            "password":{
                    "max_length":10,
                    "min_length":6,
                "error_messages":{
                        "required":"密码不能为空",
                        "min_length":"密码长度不能小于6",
                        "max_length":"密码长度不能大于10"
                },
                "validators": [checkpassword]
            }
        }
